package com.knowif.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.knowif.dao.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.knowif.dto.TutorInfoDto;
import com.knowif.enumInfo.EnterpriseTypeEnum;
import com.knowif.enumInfo.LanguageTypeEnum;
import com.knowif.enumInfo.UserEnum;
import com.knowif.enumInfo.UserOrderStatusEnum;
import com.knowif.pojo.FuzzySearch;
import com.knowif.pojo.FuzzySearchExample;
import com.knowif.pojo.Label;
import com.knowif.pojo.LabelExample;
import com.knowif.pojo.School;
import com.knowif.pojo.Special;
import com.knowif.pojo.TUser;
import com.knowif.pojo.TUserExample;
import com.knowif.pojo.Topic;
import com.knowif.pojo.TopicExample;
import com.knowif.pojo.TutorEducationInfo;
import com.knowif.pojo.TutorEducationInfoExample;
import com.knowif.pojo.TutorInfo;
import com.knowif.pojo.TutorInfoExample;
import com.knowif.pojo.UserEducationExperience;
import com.knowif.pojo.UserEducationExperienceExample;
import com.knowif.pojo.UserItem;
import com.knowif.pojo.UserItemExample;
import com.knowif.pojo.UserOrder;
import com.knowif.pojo.UserOrderExample;
import com.knowif.system.model.RestBean;
import com.knowif.util.commonUtil.StringUtil;

/**
 * @author xingyao
 * @Description: 老师dao服务层
 */
@Service
public class Tutor_service {


	@Autowired
	private TUserMapper userMapper;
	@Autowired
	private TutorInfoMapper tutorInfoMapper;


	@Autowired
	private User_service user_service;

	@Autowired
	private LabelMapper labelMapper;

	@Autowired
	private Label_service label_service;

	@Autowired
	private TopicMapper topicMapper;
	@Autowired
	private Topic_service topic_service;

	@Autowired
	private UserEducationExperienceMapper userEducationExperienceMapper;
	@Autowired
	private FuzzySearchMapper fuzzySearchMapper;

	@Autowired
	private UserOrder_service userOrder_service;
	@Autowired
	private UserEducationExperience_service educationExperience_service;
	@Autowired
	private UserItem_service userItem_service;
	@Autowired
	private TutorEducationInfoMapper tutorEducationInfoMapper;
	@Autowired
	private TutorEducationInfo_service tutorEducationInfo_service;
	@Autowired
	private UserItemMapper userItemMapper;
	@Autowired
	private School_service school_service;
	@Autowired
	private Special_service special_service;

	// 条件查询导师
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public RestBean<PageInfo> selectTutorInfo(TutorInfoExample tutorInfoExample) {
		if (tutorInfoExample == null) {
			tutorInfoExample = new TutorInfoExample();
		}

		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
		if (tutorInfos == null || tutorInfos.isEmpty()) {
			return RestBean.buildError("没有找到导师信息");
		}
		PageInfo<TutorInfo> pageInfo = new PageInfo<TutorInfo>(tutorInfos);
		List<Integer> userIds = TutorInfo.getUserIds(tutorInfos);
		List<TUser> tUsers = user_service.selectByUserIds(userIds);
		TutorInfo.saveUser(tutorInfos, tUsers);

		List<Label> labels = label_service.selectByUserIds(userIds);
		tutorInfos = TutorInfo.andLabels(tutorInfos, labels);

		List<Topic> topics = topic_service.selectTopicByUserIds(userIds);
		tutorInfos = TutorInfo.andTopics(tutorInfos, topics);

		List<UserItem> userItems = userItem_service.selectByUserIds(userIds);
		List<TutorEducationInfo> tutorEducationInfos = tutorEducationInfo_service.selectByItemIds(UserItem.getIds(userItems));
		UserItem.saveTutorEducationInfo(userItems, tutorEducationInfos);
		TutorInfo.saveUserItem(tutorInfos, userItems);

		List<UserEducationExperience> educationExperiences = educationExperience_service.selectByTutorIds(TutorInfo.getTutorIds(tutorInfos));
		tutorInfos = TutorInfo.andUserEducationExperiences(tutorInfos, educationExperiences);
		return RestBean.buildSuccess(pageInfo);
	}

	// 后台查询导师
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public RestBean<PageInfo> selectTutorInfo(Map<String, Object> params) {
		List<TutorInfo> tutorInfos = tutorInfoMapper.backendScreen(params);
		if (tutorInfos == null || tutorInfos.isEmpty()) {
			return RestBean.buildError("没有找到导师信息");
		}
		PageInfo<TutorInfo> pageInfo = new PageInfo<TutorInfo>(tutorInfos);
		List<Integer> userIds = TutorInfo.getUserIds(tutorInfos);
		List<TUser> tUsers = user_service.selectByUserIds(userIds);
		TutorInfo.saveUser(tutorInfos, tUsers);

		List<Label> labels = label_service.selectByUserIds(userIds);
		tutorInfos = TutorInfo.andLabels(tutorInfos, labels);

		List<Topic> topics = topic_service.selectTopicByUserIds(userIds);
		tutorInfos = TutorInfo.andTopics(tutorInfos, topics);

		List<UserItem> userItems = userItem_service.selectByUserIds(userIds);
		List<TutorEducationInfo> tutorEducationInfos = tutorEducationInfo_service.selectByItemIds(UserItem.getIds(userItems));
		UserItem.saveTutorEducationInfo(userItems, tutorEducationInfos);
		TutorInfo.saveUserItem(tutorInfos, userItems);

		List<UserEducationExperience> educationExperiences = educationExperience_service.selectByTutorIds(TutorInfo.getTutorIds(tutorInfos));
		tutorInfos = TutorInfo.andUserEducationExperiences(tutorInfos, educationExperiences);
		return RestBean.buildSuccess(pageInfo);
	}

	/**
	 * @author: xingyao
	 * @Description: 通过用户的信息查找导师的信息
	 * @param tUserExample
	 * @return
	 */
	public List<TutorInfo> selectBytUserExample(TUserExample tUserExample) {
		if (tUserExample == null) {
			return null;
		}
		List<TUser> tUsers = user_service.selectByTUserExampleAndNOTVirtualUser(tUserExample);
		List<Integer> userIds = TUser.getUserIds(tUsers);
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdIn(userIds);
		return selectTutor(tutorInfoExample);
	}

	/**
	 * @author: xingyao
	 * @Description: 通过用户id查找导师的信息
	 * @param userIds
	 * @return
	 */
	public List<TutorInfo> selectByUserIds(List<Integer> userIds) {
		if (userIds == null || userIds.isEmpty()) {
			return null;
		}
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdIn(userIds);
		return selectTutor(tutorInfoExample);
	}


	/**
	 * @author: xingyao
	 * @Description: 通过用户id查找导师的信息
	 * @param userId
	 * @return
	 */
	public List<TutorInfo> selectByUserId(Integer userId) {
		if (userId == null) {
			return null;
		}
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(userId);
		return tutorInfoMapper.selectByExample(tutorInfoExample);
	}


	/**
	 * @author: xingyao
	 * @Description:  通过导师id查找导师信息
	 * @param tutorId
	 * @return
	 */
	public TutorInfo selectByTutorId(Integer tutorId){
	    //重点：这个tutorId全段传的是user_id
		if (tutorId == null) {
			return null;
		}
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(tutorId);
        List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
        if(tutorInfos != null && tutorInfos.size() == 1){
            return selectTutor(tutorInfos.get(0).getId());
        }
        return null;
	}

	// 条件查询导师
	public TutorInfo selectTutor(Integer tutorId) {
		if (tutorId == null) {
			return null;
		}

		TutorInfo tutorInfo = tutorInfoMapper.selectByPrimaryKey(tutorId);
		if (tutorInfo == null) {
			return null;
		}
		TUser tuser = user_service.selectById(tutorInfo.getUserId());
		tutorInfo.settUser(tuser);

		List<Label> labels = label_service.selectByUserId(tuser.getId());
		tutorInfo.setLabel(labels);

		TopicExample topicExample = new TopicExample();
		topicExample.createCriteria().andUserIdEqualTo(tuser.getId());
		List<Topic> topics = topicMapper.selectByExample(topicExample);
		tutorInfo.setTopic(topics);


		List<UserEducationExperience> educationExperiences = educationExperience_service.selectByUserInfoId(tutorId);
		tutorInfo.setUserEducationExperiences(educationExperiences);
		return tutorInfo;
	}




	// 条件查询导师
	public List<TutorInfo> selectTutor(TutorInfoExample tutorInfoExample) {
		if (tutorInfoExample == null) {
			tutorInfoExample = new TutorInfoExample();
		}

		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
		if (tutorInfos == null || tutorInfos.isEmpty()) {
			return null;
		}

		List<Integer> userIds = TutorInfo.getUserIds(tutorInfos);


		List<TUser> tusers = user_service.selectByUserIds(userIds);
		tutorInfos = TutorInfo.andTUser(tutorInfos, tusers);

		List<Label> labels = label_service.selectByUserIds(userIds);
		tutorInfos = TutorInfo.andLabels(tutorInfos, labels);

		List<Topic> topics = topic_service.selectTopicByUserIds(userIds);
		tutorInfos = TutorInfo.andTopics(tutorInfos, topics);


		List<Integer> tutorIds = TutorInfo.getTutorIds(tutorInfos);
		List<UserEducationExperience> educationExperiences = educationExperience_service.selectByTutorIds(tutorIds);
		tutorInfos = TutorInfo.andUserEducationExperiences(tutorInfos, educationExperiences);

		List<TutorEducationInfo> tutorEducationInfos = tutorEducationInfo_service.selectByTutorIds(tutorIds);
		tutorInfos = TutorInfo.andTutorEducationInfos(tutorInfos, tutorEducationInfos);

		return tutorInfos;
	}

	/**
	 * @author: xingyao
	 * @Description: 删除导师功能，这里需要注意的时，删除这名导师需要删除模糊查询表里面的数据，并且要将未完成了转账进行完毕(
	 *               暂时转账功能没有实现)
	 * @param tUerId
	 * @return
	 */
	public RestBean<?> deleteTutor(Integer tUerId) {
	    TUserExample tUserExample = new TUserExample();
	    tUserExample.createCriteria().andIdEqualTo(tUerId);
        TUser tUser = userMapper.selectByPrimaryKey(tUerId);
        if(tUser == null){
            return RestBean.buildError("导师不存在");
        }

        TutorInfoExample tutorInfoExample = new TutorInfoExample();
        tutorInfoExample.createCriteria().andUserIdEqualTo(tUerId);
        List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
        if(tutorInfos != null && tutorInfos.size() > 1){
            return RestBean.buildError("数据异常，请联系开发人员");
        }

        if(tutorInfos == null){
            return RestBean.buildError("导师不存在");
        }
        TutorInfo tutorInfo = tutorInfos.get(0);


        int userId = tutorInfo.getUserId();
		// 查询订单信息，看是否还存在未完成的订单
		List<UserOrder> userOrders = userOrder_service.selectByUserIdAndState(userId, UserOrderStatusEnum.PAID.getState());
		if (userOrders != null && !userOrders.isEmpty()) {
			return RestBean.buildError("该名导师还存在订单未完成，不能进行删除");
		}

		// 删除导师信息
		tutorInfoMapper.deleteByExample(tutorInfoExample);

		//删除分类
        UserItemExample userItemExample = new UserItemExample();
        userItemExample.createCriteria().andUserIdEqualTo(userId);
        userItemMapper.deleteByExample(userItemExample);

        //删除教育信息
        TutorEducationInfoExample tutorEducationInfoExample = new TutorEducationInfoExample();
        tutorEducationInfoExample.createCriteria().andTutorIdEqualTo(tutorInfo.getId());
        tutorInfoMapper.deleteByExample(tutorInfoExample);

		// 删除导师标签
		label_service.deleteByUserId(userId);

		// 删除话题
		TopicExample topicExample = new TopicExample();
		topicExample.createCriteria().andUserIdEqualTo(userId);
		topicMapper.deleteByExample(topicExample);

		// 删除模糊查询信息
		FuzzySearchExample fuzzySearchExample = new FuzzySearchExample();
		fuzzySearchExample.createCriteria().andUserIdEqualTo(userId);
		fuzzySearchMapper.deleteByExample(fuzzySearchExample);

		// 更新为普通用户
		tUser.setUserType(UserEnum.USER.getNumber());
		userMapper.updateByPrimaryKeySelective(tUser);

		return RestBean.buildSuccess("删除导师用户成功");
	}


	/**
	 * @author: xingyao
	 * @Description: 删除导师功能，这里需要注意的时，删除这名导师需要删除模糊查询表里面的数据，并且要将未完成了转账进行完毕(
	 *               暂时转账功能没有实现),批量删除导师信息
	 * @param userIds
	 * @return
	 */
	public RestBean<?> deleteTutors(List<Integer> userIds) {
		if (userIds == null) {
			return RestBean.buildError("请输入要删除的用户id");
		}
		// 查询订单信息，看是否还存在未完成的订单
		UserOrderExample userOrderExample = new UserOrderExample();
		userOrderExample.createCriteria().andUserIdIn(userIds).andStatusEqualTo(UserOrderStatusEnum.PAID.getState());
		List<UserOrder> userOrders = userOrder_service.selectByExampleAndNotVirtual(userOrderExample);
		if (userOrders != null && !userOrders.isEmpty()) {
			return RestBean.buildError("该名导师还存在订单未完成，不能进行删除");
		}

		// 查看是否存在该名导师还有订单未完成
		userOrderExample = new UserOrderExample();
		userOrderExample.createCriteria().andToUserIdIn(userIds).andStatusEqualTo(UserOrderStatusEnum.PAID.getState());
		userOrders = userOrder_service.selectByExampleAndNotVirtual(userOrderExample);
		if (userOrders != null && !userOrders.isEmpty()) {
			return RestBean.buildError("该名导师还存在未处理的订单，不能进行删除");
		}

		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdIn(userIds);

		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
		if (tutorInfos == null || tutorInfos.isEmpty()) {
			return RestBean.buildError("该名导师的信息不存在");
		}
		tutorInfoMapper.deleteByExample(tutorInfoExample);

		userIds = TutorInfo.getUserIds(tutorInfos);
		List<Integer> tutorIds = TutorInfo.getTutorIds(tutorInfos);
		// 删除导师学习经历
		UserEducationExperienceExample educationExperienceExample = new UserEducationExperienceExample();
		educationExperienceExample.createCriteria().andUserInfoIdIn(tutorIds);
		userEducationExperienceMapper.deleteByExample(educationExperienceExample);

		// 删除导师标签
		label_service.deleteByUserIds(userIds);

		// 删除话题
		TopicExample topicExample = new TopicExample();
		topicExample.createCriteria().andUserIdIn(userIds);
		topicMapper.deleteByExample(topicExample);

		// 删除模糊查询信息
		FuzzySearchExample fuzzySearchExample = new FuzzySearchExample();
		fuzzySearchExample.createCriteria().andUserIdIn(userIds);
		fuzzySearchMapper.deleteByExample(fuzzySearchExample);

		return RestBean.buildSuccess("删除导师用户成功");
	}

	/**
	 * @author: xingyao
	 * @Description: 保存导师信息
	 * @param tutorInfo
	 * @return
	 */
	@Transactional
	public RestBean<?> saveTutor(TutorInfo tutorInfo) {
		if (tutorInfo == null) {
			return RestBean.buildError("添加的导师不能为空");
		}
		// 通过userId查找tutorInfo，如果存在，则不需要执行插入操作
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(tutorInfo.getUserId());
		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
		if (tutorInfos != null && !tutorInfos.isEmpty()) {
			return RestBean.buildError("该名用户已经是导师了");
		}
		// 如果还不是导师。则需要进行将用户的角色改为导师
		TUser tUser = new TUser();
		tUser.setUserType(UserEnum.TUTOR.getNumber());
		TUserExample tUserExample = new TUserExample();
		tUserExample.createCriteria().andIdEqualTo(tutorInfo.getUserId());
		int result = userMapper.updateByExampleSelective(tUser, tUserExample);

		if (result != 1) {
			// 将改名用户更新成为导师失败，则需要报错
			return RestBean.buildError("系统出错，请稍后再试");
		}

		// 同时将该用户查出来
		tUser = userMapper.selectByPrimaryKey(tutorInfo.getUserId());
		tutorInfo.settUser(tUser);
		// 更新成功，则需要插入数据
		int userInfoId = tutorInfoMapper.insert(tutorInfo);
		if (tutorInfo.getUserEducationExperiences() != null && !tutorInfo.getUserEducationExperiences().isEmpty()) {
			// 插入教育经历
			for (UserEducationExperience userEducationExperience : tutorInfo.getUserEducationExperiences()) {
				userEducationExperience.setUserInfoId(userInfoId);
				userEducationExperienceMapper.insert(userEducationExperience);
			}
		}
		if (tutorInfo.getLabel() != null && !tutorInfo.getLabel().isEmpty()) {
			// 插入标签
			for (Label label : tutorInfo.getLabel()) {
				label.setUserId(tutorInfo.getUserId());
				label_service.save(label);
			}
		}
		if (tutorInfo.getTopic() != null && !tutorInfo.getTopic().isEmpty()) {
			// 插入擅长话题
			for (Topic topic : tutorInfo.getTopic()) {
				topic.setUserId(tutorInfo.getUserId());
				topicMapper.insert(topic);
			}
		}
		// 并且将数据添加到模糊查询表中
		List<FuzzySearch> fuzzySearchs = FuzzySearch.Tutor2FuzzySearch(tutorInfo);
		if (fuzzySearchs != null && !fuzzySearchs.isEmpty()) {
			for (FuzzySearch fuzzySearch : fuzzySearchs) {
				fuzzySearchMapper.insert(fuzzySearch);
			}
		}
		return RestBean.buildSuccess("添加导师成功");
	}

	/**
	 * @author: xingyao
	 * @Description: 导师自我发布
	 * @param tutorInfo
	 * @return
	 */
	@Transactional
	public RestBean<?> saveSelfPublishTutor(TutorInfo tutorInfo, String contact) {
		// 如果还不是导师。则需要进行将用户的角色改为导师
		TUser tUser = new TUser();
		tUser.setUserType(UserEnum.SELFPUBLISH_USER.getNumber());
		TUserExample tUserExample = new TUserExample();
		tUserExample.createCriteria().andIdEqualTo(tutorInfo.getUserId());
		tUser.setWechatNum(contact);
		userMapper.updateByExampleSelective(tUser, tUserExample);

		// 同时将该用户查出来
		tUser = userMapper.selectByPrimaryKey(tutorInfo.getUserId());
		tutorInfo.settUser(tUser);
		// 更新成功，则需要插入数据
		tutorInfoMapper.insert(tutorInfo);

		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(tutorInfo.getUserId());
		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
		if(tutorInfos.isEmpty()){
			return RestBean.buildError("发布失败");
		}

		tutorInfo.getTutorEducationInfo().setTutorId(tutorInfos.get(0).getId());
		tutorEducationInfoMapper.insert(tutorInfo.getTutorEducationInfo());
		// 并且将数据添加到模糊查询表中
		List<FuzzySearch> fuzzySearchs = FuzzySearch.Tutor2FuzzySearch(tutorInfo);
		if (fuzzySearchs != null && !fuzzySearchs.isEmpty()) {
			for (FuzzySearch fuzzySearch : fuzzySearchs) {
				fuzzySearchMapper.insert(fuzzySearch);
			}
		}
		return RestBean.buildSuccess("添加导师成功");
	}

	/**
	 * @author: xh
	 * @Description: 保存导师信息
	 * @param tutorInfoDto
	 * @return
	 */
	@Transactional
	public RestBean<?> saveTutor(TutorInfoDto tutorInfoDto) {
		buildFlashPoint(tutorInfoDto);
		if (tutorInfoDto == null) {
			return RestBean.buildError("添加的导师不能为空");
		}
		TUserExample tUserExample = new TUserExample();
		tUserExample.createCriteria().andOpenidEqualTo(tutorInfoDto.getOpenid());
		List<TUser> users = user_service.selectByTUserExampleAndNOTVirtualUser(tUserExample);
		if(users == null || users.size() != 1){
			return RestBean.buildError("openid不存在");
		}
		TUser tUser = users.get(0);
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(tUser.getId());
		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
		if(tutorInfos != null && tutorInfos.size() > 0){
			return RestBean.buildError("导师信息已存在");
		}
		// 添加导师信息表信息
		TutorInfo tutorInfo = new TutorInfo();
		BeanUtils.copyProperties(tutorInfoDto, tutorInfo);
		tutorInfo.setHelpsNum(0);
		tutorInfo.setTotalIncome(0.0);
		tutorInfo.setTotalScore(0.0);
		tutorInfo.setIsOpenTalk(0);
		tutorInfo.setBeCollectedNum(0);
		tutorInfo.setUserId(tUser.getId());
		tutorInfoMapper.insert(tutorInfo);
		tUser.setUserType(UserEnum.TUTOR.getNumber());
		BeanUtils.copyProperties(tutorInfoDto, tUser);
		//更新用户信息
		userMapper.updateByPrimaryKeySelective(tUser);
		//添加导师信息
		addTutor(tUser, tutorInfoDto, tutorInfo);
		return RestBean.buildSuccess("添加导师成功");
	}

	/**
	 * @author: xh
	 * @Description: 保存导师信息
	 * @param tutorInfoDto
	 * @return
	 */
	@Transactional
	public RestBean<?> updateTutor(TutorInfoDto tutorInfoDto) {
		buildFlashPoint(tutorInfoDto);
		if (tutorInfoDto == null) {
			return RestBean.buildError("添加的导师不能为空");
		}
		TUserExample tUserExample = new TUserExample();
		tUserExample.createCriteria().andOpenidEqualTo(tutorInfoDto.getOpenid());
		List<TUser> users = user_service.selectByTUserExampleAndNOTVirtualUser(tUserExample);
		if(users == null || users.size() != 1){
			return RestBean.buildError("数据错误，添加失败");
		}
		TUser tUser = users.get(0);
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(tUser.getId());
		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
		TutorInfo tutorInfo = tutorInfos.get(0);
		BeanUtils.copyProperties(tutorInfoDto, tutorInfo);
		// 更新导师信息表信息
		tutorInfoMapper.updateByPrimaryKeySelective(tutorInfo);
		tUser.setUserType(UserEnum.TUTOR.getNumber());
		BeanUtils.copyProperties(tutorInfoDto, tUser);
		//更新用户信息
		userMapper.updateByPrimaryKeySelective(tUser);
		//添加导师信息
		updateTutor(tUser, tutorInfoDto, tutorInfo);
		return RestBean.buildSuccess("添加导师成功");
	}

	private void updateTutor(TUser tUser, TutorInfoDto tutorInfoDto, TutorInfo tutorInfo) {
		//添加标签信息
		LabelExample labelExample = new LabelExample();
		labelExample.createCriteria().andUserIdEqualTo(tUser.getId());
		labelMapper.deleteByExample(labelExample);
		List<Label> labels = tutorInfoDto.getLabel();
		if(labels != null && labels.size() > 0){
			labels.forEach(label -> {
				label.setUserId(tUser.getId());
				labelMapper.insert(label);
			});
		}
		//添加导师话题信息
		List<Topic> topics = tutorInfoDto.getTopic();
		if(topics != null && topics.size() > 0){
			topics.forEach(topic -> {
				topic.setUserId(tUser.getId());
				if(topic.getId() != null && topic.getId() != 0){
					topicMapper.updateByPrimaryKeySelective(topic);
				}else{
					topic.setDealNum(0);
					topicMapper.insert(topic);
				}

			});
		}

		//删除之前相关的类目信息
		UserItemExample userItemExample = new UserItemExample();
		userItemExample.createCriteria().andUserIdEqualTo(tUser.getId());
		userItemMapper.deleteByExample(userItemExample);
		//删除学校信息
		TutorEducationInfoExample tutorEducationInfoExample = new TutorEducationInfoExample();
		tutorEducationInfoExample.createCriteria().andTutorIdEqualTo(tutorInfo.getId());
		tutorEducationInfoMapper.deleteByExample(tutorEducationInfoExample);
		//删除模糊查询
		FuzzySearchExample fuzzySearchExample = new FuzzySearchExample();
		fuzzySearchExample.createCriteria().andUserIdEqualTo(tUser.getId());
		fuzzySearchMapper.deleteByExample(fuzzySearchExample);

		List<UserItem> userItems = tutorInfoDto.getUserItems();
		List<School> schools = school_service.selectSchoolBySchoolIds(UserItem.getSchools(userItems));
		List<Special> specials = special_service.selectSpecialBySpecialds(UserItem.getSpecialIds(userItems));

		if (userItems != null && userItems.size() > 0){
			userItems.forEach(userItem -> {
				userItem.setUserId(tUser.getId());
				userItemMapper.insert(userItem);
				//非校招和语言考试
				if(userItem.getLanguageType() == null && userItem.getEnterpriseType() == null){
					TutorEducationInfo tutorEducationInfo = userItem.getTutorEducationInfo();
					if(tutorEducationInfo != null){
						tutorEducationInfo.setUserItemId(userItem.getId());
						tutorEducationInfo.setTutorId(tutorInfo.getId());
						tutorEducationInfo.setUserItemId(userItem.getId());
						String schoolName = School.getSchoolName(schools, userItem.getTutorEducationInfo().getSchoolId());
						String specialName = Special.getSpecialName(specials, userItem.getTutorEducationInfo().getSpecialId());
						tutorEducationInfo.setSchoolName(schoolName);
						tutorEducationInfo.setSpecialName(specialName);
						tutorEducationInfoMapper.insert(tutorEducationInfo);
					}
				}
			});
		}
		tutorInfo.setUserItem(userItems);
		tutorInfo.settUser(tUser);
		tutorInfo.setTopic(topics);
		tutorInfo.setLabel(labels);
		// 并且将数据添加到模糊查询表中
		List<FuzzySearch> fuzzySearchs = FuzzySearch.Tutor2FuzzySearch(tutorInfo);
		if (fuzzySearchs != null && !fuzzySearchs.isEmpty()) {
			for (FuzzySearch fuzzySearch : fuzzySearchs) {
				fuzzySearchMapper.insert(fuzzySearch);
			}
		}
	}

	private void buildFlashPoint(TutorInfoDto tutorInfoDto) {
		Map<Integer,String> languageTypeMap = LanguageTypeEnum.getLanguageTypes();
		Map<Integer,String> enterpriseType = EnterpriseTypeEnum.getEnterpriseTypeMap();
		List<UserItem> userItems = tutorInfoDto.getUserItems();
		List<School> schools = school_service.selectSchoolBySchoolIds(UserItem.getSchools(userItems));
		List<Special> specials = special_service.selectSpecialBySpecialds(UserItem.getSpecialIds(userItems));
		if(userItems != null && !userItems.isEmpty()){
			for(UserItem userItem : userItems){
				if((userItem.getItemId() == 1 || userItem.getItemId() == 4) && userItem.getTutorEducationInfo() != null){
					String schoolName = School.getSchoolName(schools, userItem.getTutorEducationInfo().getSchoolId());
					String specialName = Special.getSpecialName(specials, userItem.getTutorEducationInfo().getSpecialId());
					tutorInfoDto.setFlashPoint(schoolName +" " + specialName);
				}else if(userItem.getItemId() == 2 && userItem.getTutorEducationInfo() != null){
					String schoolName = School.getSchoolName(schools, userItem.getTutorEducationInfo().getSchoolId());
					String countryName = School.getcountryName(schools, userItem.getTutorEducationInfo().getSchoolId());
					tutorInfoDto.setFlashPoint(countryName+ " "+schoolName);
				}
			}
		}
	}

	/**
	 * 删除导师基本信息
	 * @param tutorInfo
	 */
	public void deleteTutorBase(TutorInfo tutorInfo){
		// 删除导师标签
		LabelExample labelExample = new LabelExample();
		labelExample.createCriteria().andUserIdEqualTo(tutorInfo.getUserId());
		labelMapper.deleteByExample(labelExample);

		// 删除话题
		TopicExample topicExample = new TopicExample();
		topicExample.createCriteria().andUserIdEqualTo(tutorInfo.getUserId());
		topicMapper.deleteByExample(topicExample);


		// 删除模糊查询信息
		FuzzySearchExample fuzzySearchExample = new FuzzySearchExample();
		fuzzySearchExample.createCriteria().andUserIdEqualTo(tutorInfo.getUserId());
		fuzzySearchMapper.deleteByExample(fuzzySearchExample);

		//删除类目信息
		UserItemExample userItemExample = new UserItemExample();
		userItemExample.createCriteria().andUserIdEqualTo(tutorInfo.getUserId());
		userItemMapper.deleteByExample(userItemExample);

		//删除学校信息
		TutorEducationInfoExample educationInfoExample = new TutorEducationInfoExample();
		educationInfoExample.createCriteria().andTutorIdEqualTo(tutorInfo.getId());
		tutorEducationInfoMapper.deleteByExample(educationInfoExample);
	}

	public void addTutor(TUser tUser, TutorInfoDto tutorInfoDto, TutorInfo tutorInfo){
		//添加标签信息
		List<Label> labels = tutorInfoDto.getLabel();
		if(labels != null && labels.size() > 0){
			labels.forEach(label -> {
				label.setUserId(tUser.getId());
				labelMapper.insert(label);
			});
		}
		//添加导师话题信息
		List<Topic> topics = tutorInfoDto.getTopic();
		if(topics != null && topics.size() > 0){
			topics.forEach(topic -> {
				topic.setUserId(tUser.getId());
				topic.setDealNum(0);
				topicMapper.insert(topic);
			});
		}

		List<UserItem> userItems = tutorInfoDto.getUserItems();
		List<School> schools = school_service.selectSchoolBySchoolIds(UserItem.getSchools(userItems));
		List<Special> specials = special_service.selectSpecialBySpecialds(UserItem.getSpecialIds(userItems));

		if (userItems != null && userItems.size() > 0){
			userItems.forEach(userItem -> {
				userItem.setUserId(tUser.getId());
				userItemMapper.insert(userItem);
				if(userItem.getTutorEducationInfo() != null){
					TutorEducationInfo tutorEducationInfo = userItem.getTutorEducationInfo();
					if(tutorEducationInfo != null){
						tutorEducationInfo.setUserItemId(userItem.getId());
						tutorEducationInfo.setTutorId(tutorInfo.getId());
						tutorEducationInfo.setUserItemId(userItem.getId());
						String schoolName = School.getSchoolName(schools, userItem.getTutorEducationInfo().getSchoolId());
						String specialName = Special.getSpecialName(specials, userItem.getTutorEducationInfo().getSpecialId());
						tutorEducationInfo.setSchoolName(schoolName);
						tutorEducationInfo.setSpecialName(specialName);
						tutorEducationInfoMapper.insert(tutorEducationInfo);
					}
				}
			});
		}

		tutorInfo.setUserItem(userItems);
		tutorInfo.settUser(tUser);
		tutorInfo.setTopic(topics);
		tutorInfo.setLabel(labels);
		// 并且将数据添加到模糊查询表中
		List<FuzzySearch> fuzzySearchs = FuzzySearch.Tutor2FuzzySearch(tutorInfo);
		if (fuzzySearchs != null && !fuzzySearchs.isEmpty()) {
			for (FuzzySearch fuzzySearch : fuzzySearchs) {
				fuzzySearchMapper.insert(fuzzySearch);
			}
		}
	}

	/**
	 * @author: xingyao
	 * @Description: 通过城市名称、学院名称、学校所在城市进行导师信息查找
	 * @param city
	 * @param college
	 * @param school_city
	 * @return
	 */
	public RestBean<?> selectByCondition(int itemId, String city, String college, String school_city) {
		if (StringUtil.isEmpty(itemId+"") && (StringUtil.isEmpty(city) || StringUtil.isEmpty(college) || StringUtil.isEmpty(school_city))) {
			return RestBean.buildError("请输入查询条件");
		}

		List<UserItem> userItems = userItem_service.selectUserItemById(itemId);
		List<Integer> tutorIds = UserItem.getTutorIds(userItems);
		List<TutorInfo> tutorInfos = new ArrayList<TutorInfo>();
		if (!StringUtil.isEmpty(school_city)) {
			TutorInfoExample tutorInfoExample = new TutorInfoExample();
			tutorInfoExample.createCriteria().andLocationEqualTo(city).andIdIn(tutorIds);
			tutorInfos = selectTutor(tutorInfoExample);
		}
		List<TutorInfo> result = new ArrayList<TutorInfo>();
		if (tutorInfos == null || tutorInfos.isEmpty()) {
			UserEducationExperienceExample example = new UserEducationExperienceExample();
			example.createCriteria().andCollegeEqualTo(college).andSchoolCityEqualTo(school_city);
			List<UserEducationExperience> userEducationExperiences = educationExperience_service
					.selectByExample(example);
			if (userEducationExperiences == null || userEducationExperiences.isEmpty()) {
				return RestBean.buildError("很抱歉，未找到匹配的导师！导师不断上新中，试试联系客服说出的你的需求会更快哦");
			}

			List<Integer> userIds = new ArrayList<Integer>();
			for (UserEducationExperience educationExperience : userEducationExperiences) {
				userIds.add(educationExperience.getUserInfoId());
			}
			result = selectByUserIds(userIds);
		} else {
			for (TutorInfo info : tutorInfos) {
				education: {
					if (!StringUtil.isEmpty(college)) {
						for (UserEducationExperience educationExperience : info.getUserEducationExperiences()) {
							if (college.equals(educationExperience.getCollege())) {
								result.add(info);
								break education;
							}
						}
					}
					if (!StringUtil.isEmpty(school_city)) {
						for (UserEducationExperience educationExperience : info.getUserEducationExperiences()) {
							if (school_city.equals(educationExperience.getSchoolCity())) {
								result.add(info);
								break education;
							}
						}
					}
				}
			}
		}
		if (result.isEmpty()) {
			return RestBean.buildError("很抱歉，未找到匹配的导师！导师不断上新中，试试联系客服说出的你的需求会更快哦");
		} else {
			return RestBean.buildSuccess(result);
		}
	}

	/**
	 * 更新不为空的item属性
	 * @param tutorInfo
	 * @return
	 */
	public int updateTutorNotNull(TutorInfo tutorInfo){
		return tutorInfoMapper.updateByPrimaryKeySelective(tutorInfo);
	}

	/**
	 * 更新所有item属性
	 * @param tutorInfo
	 * @return
	 */
	public int updateTutor(TutorInfo tutorInfo){
		return tutorInfoMapper.updateByPrimaryKey(tutorInfo);
	}



	/**
	 * 导师筛选
	 * @param params
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	public PageInfo<TutorInfo> screen(Map<String, Object> params, int pageSize, int pageNum){
		PageHelper.startPage(pageNum, pageSize);
		List<TutorInfo> tutorInfos = tutorInfoMapper.screen(params);

		List<Integer> userIds = TutorInfo.getUserIds(tutorInfos);

		List<TUser> tUsers = user_service.selectByUserIds(userIds);
		TutorInfo.saveUser(tutorInfos, tUsers);

		List<Topic> topics = topic_service.selectTopicByUserIds(userIds);
		TutorInfo.saveTopics(tutorInfos, topics);

		//标签
		List<Label> labels = label_service.selectByUserIds(userIds);
		TutorInfo.saveLabels(tutorInfos, labels);

		List<UserEducationExperience> userEducationExperiences = educationExperience_service.selectByTutorIds(TutorInfo.getTutorIds(tutorInfos));
		TutorInfo.saveUserEducationExperiences(tutorInfos, userEducationExperiences);

		//教育信息
		List<TutorEducationInfo> educationInfos = tutorEducationInfo_service.selectByTutorIds(TutorInfo.getTutorIds(tutorInfos));
		TutorInfo.andTutorEducationInfos(tutorInfos, educationInfos);

		PageInfo<TutorInfo> pageInfo = new PageInfo<TutorInfo>(tutorInfos);
		return pageInfo;
	}


	public RestBean<?> selectTutorByItem(UserItemExample example){
		List<UserItem> userItems = userItemMapper.selectByExample(example);
		if(userItems == null || userItems.isEmpty()){
			return RestBean.buildError("请输入要查找的分类id");
		}
		List<Integer> tutorIds = UserItem.getTutorIds(userItems);
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andIdIn(tutorIds);
		return selectTutorInfo(tutorInfoExample);
	}



}
























